package com.sunnada.edu.system.sysuser.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.sunnada.edu.system.pub.common.BasicController;
import com.sunnada.edu.system.pub.common.Common;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.dao.Page;
import com.sunnada.edu.system.pub.filter.XssHttpServletRequestWrapper;
import com.sunnada.edu.system.pub.service.PubMethods;
import com.sunnada.edu.system.pub.util.Utils;
import com.sunnada.edu.system.sysuser.bean.SysUser;
import com.sunnada.edu.system.sysuser.service.SysUserService;

/***
 * explain 用户控制层
 * 
 * @author chs 2015-5-12 version 1.0
 */
@Controller
@RequestMapping("/sysuserController")
public class SysUserController extends BasicController {
	@Resource
	SysUserService userService;

	/** 用户首页 */
	@RequestMapping("/user")
	public String user(HttpServletRequest request) {
		String curr = request.getParameter("curr");
		request.setAttribute("curr", curr);
		// 当前路径
		String moduleId = request.getParameter("moduleId");
		request.setAttribute("pathValue", PubMethods.getPathValue(moduleId));
		return "system/sysuser/sysuser";
	}

	/** 用户查询 */
	@RequestMapping("/userSearch")
	public void userSearch(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		Page page = new Page();
		page.setRowCount(userService.getUserCots(params));
		page.setPageMap(request, page, params);
		List<?> userList = userService.findUsers(params);
		JSONObject json = new JSONObject();
		json.put("list", userList);
		json.put("params", params);
		printInfo(response, json);
	}

	/** 用户添加页面 */
	@RequestMapping("/userAdd")
	public String userAdd(HttpServletRequest request) {
		HashMap<String, String> params = new HashMap<String, String>();
		return "system/sysuser/sysuser_add";
	}

	/** 用户修改页面 */
	@RequestMapping("/userUpdate")
	public String userUpdate(HttpServletRequest request) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		Map user = userService.getUserByRecId(params);
		request.setAttribute("user", user);
		return "system/sysuser/sysuser_update";
	}

	/** 用户保存功能 */
	@RequestMapping("/userSave")
	public void userSave(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		// 验证用户账号是否重复
		String recId = params.get("recId");
		if (Utils.isNotNull(recId)) {
			params.put("userId", recId);
			msg = userService.userUpdate(params);
		} else {
			String phone = params.get("phone");
			params.put("userLoginCode", phone);// 第一次添加，手机号作为登录账号
			String userId = phone;
			String pwd = phone.substring(phone.length() - 6, phone.length());
			String password = MD5.md5(userId + pwd);
			params.put("loginPwd", password);// 默认密码
			params.put("recId", userId);
			msg = userService.userAdd(params);
		}
		printInfo(response, msg);
	}

	/** 用户删除功能 */
	@RequestMapping("/userDelete")
	public void userDelete(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		String recIds = request.getParameter("recIds");
		params.put("recIds", Utils.getSqlSplitStr(recIds));
		msg = userService.userDelete(params);
		printInfo(response, msg);
	}

	/** 用户重置密码功能 */
	@RequestMapping("/resetPwd")
	public void resetPwd(HttpServletRequest request, HttpServletResponse response) {
		JSONObject returnJson = new JSONObject();
		HashMap<String, String> params = new HashMap<String, String>();
		String recIds = request.getParameter("recIds");
		params.put("recIds", recIds);
		msg = userService.resetPwd(params);
		printInfo(response, msg);
	}

	/** 用户授权页面 */
	@RequestMapping("/grentPage")
	public String grentPage(HttpServletRequest request) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		// 查找当前用户有哪些角色
		List<HashMap<String, String>> roleList = userService.getMyRoleList(params);
		request.setAttribute("roleList", roleList);
		request.setAttribute("userId", params.get("userId"));
		request.setAttribute("loginUserId", params.get("loginUserId"));
		return "system/sysuser/sysuser_set_role";
	}

	/** 所选用户有哪些权限 */
	@RequestMapping("/getSelectUserRoles")
	public void getSelectUserRoles(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		String userId = request.getParameter("userId");
		params.put("userId", userId);
		List userRoles = userService.getSelectUserRole(params);
		JSONObject json = new JSONObject();
		json.put("userRoles", userRoles);
		json.put("params", params);
		printInfo(response, json);
	}

	/** 用户授权 */
	@RequestMapping("/roleAdd")
	public void roleAdd(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		String roleIds = request.getParameter("roleIds");
		String userId = request.getParameter("userId");
		String roleLost = request.getParameter("roleLost");
		params.put("userId", userId);
		params.put("roleIds", roleIds);
		params.put("roleLost", roleLost);
		msg = userService.grentRoleToUser(params);
		printInfo(response, msg);
	}

	/** 用户停用 */
	@RequestMapping("/userDisable")
	public void userDisable(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		String recIds = request.getParameter("recIds");
		params.put("recIds", Utils.getSqlSplitStr(recIds));
		msg = userService.userDisables(params);
		printInfo(response, msg);
	}

	/** 用户启用 */
	@RequestMapping("/userEnable")
	public void userEnable(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		String recIds = request.getParameter("recIds");
		params.put("recIds", Utils.getSqlSplitStr(recIds));
		msg = userService.userEnables(params);
		printInfo(response, msg);
	}

	/** 用户导出 */
	@RequestMapping("/exportSysUser")
	public void exportSysUser(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		try {
			userService.exportSysUser(params, request, response);
		} catch (Exception e) {
			printInfo(response, "<script>alert('导出失败，请稍后重试！');window.history.go(-1);</script>");
		}
	}

	/**用户信息导入记录界面 */
	@RequestMapping("/sysuserImportpage")
	public String sysuserImportpage(HttpServletRequest request) {
		return "system/sysuser/sysuserImportpage";
	}

	/** 用户导入 */
	@RequestMapping("/sysUserImport")
	public void sysUserImport(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		HttpServletRequest re = XssHttpServletRequestWrapper.getOrgRequest(request);
		setReqParams(re, SysUser.class, params);
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("fileField");
		try {
			userService.sysUserImport(file, params, request, response);
		} catch (Exception e) {
			printInfo(response, "<script>alert('导出失败，请稍后重试！');window.history.go(-1);</script>");
		}
	}

	/** 用户信息模板导出 */
	@RequestMapping("/sysUserModelExport")
	public void sysUserModelExport(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		try {
			userService.sysUserModelExport(params, request, response);
		} catch (Exception e) {
			printInfo(response, "<script>alert('用户信息模板导出失败，请稍后重试！');window.history.go(-1);</script>");
		}
	}
	
	
	/**
     * 合同保存
     * 
     * @param response
     * @param request
     */
    @RequestMapping("/contractSave")
    public void contractSave(HttpServletResponse response, HttpServletRequest request) {
        HashMap<String, String> params = new HashMap<String, String>();
        setReqParams(request, null, params);

        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request
                .getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                // 存文件
                //String savePath = contractService.FileSave(file,request);
                String fileName = file.getOriginalFilename();
   
            }
        }
        printInfo(response, msg);
    }
    
    /** 角色权限查询 */
	@RequestMapping("/getRolePower")
	public void getRolePower(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, SysUser.class, params);
		List<?> userList = userService.getRolePower(params);
		JSONObject json = new JSONObject();
		json.put("list", userList);
		printInfo(response, json);
	}

}
